import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  user: {},
  menus: [],
  btns: [],
  // name: '',
  avatar: '',
  // introduction: '',
  // roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_BTNS: (state, btns) => {
    state.btns = btns
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  // SET_ROLES: (state, roles) => {
  //   state.roles = roles
  // }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { mobile, password, captcha } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: mobile.trim(), password, captcha }).then(response => {
        console.log(response, 'res');
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        console.log(response, 'info');
        const { userInfo } = response
        const {user, menus, btns} = userInfo
        if (!user) {
          reject('认证失败，请重新登录')
        }

        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!menus || menus.length <= 0) {
          reject('权限不能为空,请先获取权限')
        }

        commit('SET_MENUS', menus)
        commit('SET_BTNS', btns)
        commit('SET_USER', user)
        
        resolve(userInfo)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER', {})
        commit('SET_MENUS', [])
        commit('SET_BTNS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USER', {})
      commit('SET_MENUS', [])
      commit('SET_BTNS', [])
      // commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

//   // dynamically modify permissions
//   async changeRoles({ commit, dispatch }, role) {
//     const token = role + '-token'

//     commit('SET_TOKEN', token)
//     setToken(token)

//     const { roles } = await dispatch('getInfo')

//     resetRouter()

//     // generate accessible routes map based on roles
//     const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
//     // dynamically add accessible routes
//     router.addRoutes(accessRoutes)

//     // reset visited views and cached views
//     dispatch('tagsView/delAllViews', null, { root: true })
//   }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
